<template>
  <div class="app-container">
    <div class="content-main">
      <div class="form-table-box">
        <el-form
          v-loading="loading"
          ref="infoForm"
          :rules="infoRules"
          :model="infoForm"
          label-width="120px"
        >
          <el-form-item label="门店名称" prop="storeName">
            <el-input v-model="infoForm.storeName" />
          </el-form-item>
          <el-form-item label="门店图" prop="storeImageList">
            <pa-upload
              :action="action"
              :show-file-list="false"
              :limit="1"
              :headers="headers"
              :on-success="uploadPicUrl"
              :on-remove="onRemove"
              tip="建议门店图尺寸:690*400"
              list-type="picture-card"
              class="avatar-uploader"
              accept=".jpg, .jpeg, .png, .gif"
            />
          </el-form-item>
          <el-form-item label="门店简介" prop="abbr">
            <vue-ueditor-wrap
              v-model="infoForm.abbr"
              :config="ueditorConfig.config"
              @ready="ueditorConfig.ready"
            />
          </el-form-item>
          <el-form-item label="营业时间" prop="openTime">
            <el-input v-model="infoForm.openTime" />
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="infoForm.contact" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model.number="infoForm.contactPhone" />
          </el-form-item>
          <el-form-item label="固定电话" prop="tel">
            <el-input v-model="infoForm.tel" />
          </el-form-item>
          <el-form-item label="地址" prop="city">
            <el-cascader
              :options="options"
              v-model="selectedOptions"
              size="large"
              @change="addressChange"
            />
            <el-input
              v-model="infoForm.city"
              type="hidden"
              style="display: none"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <div class="flex flex-direction-r">
              <el-input v-model="infoForm.address" class="flex-1" />
              <el-button class="ml20" @click="showMap">地图选择</el-button>
            </div>
          </el-form-item>
          <el-form-item label="门店账号" prop="loginId">
            <el-input v-model="infoForm.loginId" />
          </el-form-item>
          <el-form-item label="门店密码" prop="password">
            <el-input v-model="infoForm.password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitInfo">提交</el-button>
            <el-button @click="goBack">取消</el-button>
          </el-form-item>
        </el-form>
        <el-dialog :visible.sync="dialogVisible" title="地图选择">
          <Map ref="map" />
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setMap">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import { createStore } from '@/api/store/store'
import upload from '@/components/Upload'
import Map from '@/components/Map'
import ueditorConfig from '@/config/ueditorConfig'
import { getToken } from '@/utils/auth'
import { regionData, CodeToText } from 'element-china-area-data'
export default {
  components: {
    'pa-upload': upload,
    Map,
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('管理员密码长度应大于6'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      options: regionData,
      selectedOptions: [],
      keyword: '',
      dialogVisible: false,
      center: {
        lng: 0,
        lat: 0,
      },
      zoom: 3,
      loading: false,
      action: `${process.env.BASE_API}/vms/v1/image/upload`,
      infoForm: {
        // storeId: null,
        storeName: '',
        storeImage: '',
        storeImageList: [],
        abbr: '', // 简称
        openTime: '',
        contact: '',
        contactPhone: '',
        tel: '',
        address: '',
        loginId: '',
        password: '',
        latitude: '',
        longitude: '',
        province: '',
        region: '',
        city: '',
      },
      ueditorConfig: ueditorConfig,
      infoRules: {
        storeName: [
          {
            required: true,
            message: '请输入门店名称',
            trigger: 'blur',
          },
        ],
        abbr: [
          {
            required: true,
            message: '请输入门店简介',
            trigger: 'change',
          },
        ],
        openTime: [
          {
            required: true,
            message: '请选择营业时间',
            trigger: 'change',
          },
        ],
        contact: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur',
          },
        ],
        contactPhone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            message: '请输入固定电话',
            trigger: 'blur',
          },
        ],
        city: [
          {
            required: true,
            message: '请选择地址',
            trigger: 'change',
          },
        ],
        address: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur',
          },
        ],
        loginId: [
          {
            required: true,
            message: '请输入门店账号',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入门店密码',
            trigger: 'blur',
          },
          {
            validator: validatePassword,
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken(),
      }
    },
  },
  methods: {
    setMap() {
      console.log(this.$refs.map.addressKeyword)
      this.infoForm.address = this.$refs.map.addressKeyword
      this.infoForm.latitude = this.$refs.map.latitude
      this.infoForm.longitude = this.$refs.map.longitude
      this.dialogVisible = false
    },
    getCity(cb) {
      cb()
      // const key = `6REBZ-CQBK6-BLDSS-EQOOT-LZLBE-FXBDX`
      // const city =
      //   this.infoForm.province +
      //   this.infoForm.city +
      //   this.infoForm.region +
      //   this.infoForm.address
      // const url = `https://apis.map.qq.com/ws/geocoder/v1/?output=jsonp`
      // this.$jsonp(url, {
      //   key: key,
      //   address: city,
      // })
      //   .then((res) => {
      //     if (res.status === 0) {
      //       this.infoForm.latitude = res.result.location.lat
      //       this.infoForm.longitude = res.result.location.lng
      //       cb(res)
      //     } else {
      //       this.loading = false
      //       this.$message({
      //         message: '地址无法解析,请重新输入',
      //         type: 'warning',
      //       })
      //     }
      //   })
      //   .catch((err) => {
      //     this.loading = false
      //     console.log(err)
      //   })
    },
    goBack() {
      this.$router.go(-1)
    },
    onSubmitInfo() {
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          // this.infoForm[`openTime`] = parserDate(this.infoForm[`openTime`])
          this.infoForm[`storeImage`] =
            this.infoForm[`storeImageList`].length > 0
              ? this.infoForm[`storeImageList`][0].url
              : []
          if (!this.infoForm[`storeImage`].length) {
            this.$message({
              type: 'warning',
              message: '请上传门店图',
            })
            return false
          }
          this.loading = true
          this.getCity((res) => {
            createStore(this.infoForm)
              .then((response) => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: '保存成功',
                })
                this.$router.push({
                  path: '/store',
                })
              })
              .catch(() => {
                this.loading = false
              })
          })
        } else {
          return false
        }
      })
    },
    handleSuccess(response) {
      this.infoForm.storeImage = response.data.fileUrl
    },
    uploadPicUrl: function (response) {
      this.$refs['infoForm'].clearValidate('storeImage')
      this.infoForm.storeImageList.push({
        name: response.name,
        url: response.data.fileUrl,
      })
    },
    onRemove(file, fileList) {
      this.infoForm.storeImageList.forEach((item, index) => {
        if (file.url === item.url) {
          this.infoForm.storeImage.splice(index, 1)
        }
      })
    },
    addressChange(arr) {
      this.infoForm.province = CodeToText[arr[0]]
      this.infoForm.city = CodeToText[arr[1]]
      this.infoForm.region = CodeToText[arr[2]]
    },
    showMap() {
      this.dialogVisible = true
    },
  },
}
</script>

<style lang="scss">
.image-uploader {
  height: 105px;
}

.image-uploader .el-upload {
  border: 1px solid #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.image-uploader .image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 187px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.image-uploader .image-show {
  width: 187px;
  height: 105px;
  display: block;
}

.image-uploader.new-image-uploader {
  font-size: 28px;
  color: #8c939d;
  width: 165px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.image-uploader.new-image-uploader .image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 165px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.image-uploader.new-image-uploader .image-show {
  width: 165px;
  height: 105px;
  display: block;
}

.baidu-map {
  padding: 20px;
  width: 400px;
  height: 400px;

  .map {
    width: 100%;
    height: 100%;
  }
}
</style>
